package init

import (
	"ew-srv/basic/config"
	"ew-srv/handler/models"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

var err error

func InitMy() {
	Mysqlconfig := config.Appconf.Mysql
	// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", Mysqlconfig.User,
		Mysqlconfig.Password, Mysqlconfig.Host, Mysqlconfig.Port,
		Mysqlconfig.Database)

	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	} else {
		fmt.Println("数据库连接成功")
	}
	err = config.DB.AutoMigrate(&models.User{}, &models.Eclass{}, &models.EVideoass{}, &models.HomePages{})
	if err != nil {
		panic(err)
	} else {
		fmt.Println("迁移成功")
	}
	sqlDB, _ := config.DB.DB()
	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)
	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)
	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)
}
